package org.bai.algorithm.hot.hard;

import org.bai.algorithm.util.StringUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 无重复字符的最长子串
 * 给定一个字符串 s ，请你找出其中不含有重复字符的 最长子串 的长度。
 */
public class LengthOfLongestSubstring {

    public static void main(String[] args) {
//        String simpleString = StringUtil.generateSimpleString(20);
        String simpleString = "asdfgahjklzxcavbnm";
        System.out.println(simpleString);
        System.out.println(lengthOfLongestSubstring(simpleString));
    }

    public static int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> temporary = new HashMap<>(26);
        int start = 0, end = 0, sum = 0;
        int length = s.length();
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (temporary.containsKey(c)) {
                start = Math.max(temporary.get(c), start);
            }

            sum = Math.max((end - start + 1), sum);
            end = i + 1;
            temporary.put(c, end);
        }

        return sum;
    }

}
